using System;
using System.Collections.Generic;

namespace TangCaptureTraffic.Services
{
    /// <summary>
    /// 简单的服务容器，用于依赖注入和服务管理
    /// </summary>
    public class ServiceContainer
    {
        private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
        private readonly Dictionary<Type, Func<ServiceContainer, object>> _factories = new Dictionary<Type, Func<ServiceContainer, object>>();
        private static ServiceContainer _instance;
        private static readonly object _lock = new object();

        /// <summary>
        /// 获取服务容器的单例实例
        /// </summary>
        public static ServiceContainer Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new ServiceContainer();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 注册单例服务
        /// </summary>
        /// <typeparam name="TInterface">服务接口类型</typeparam>
        /// <typeparam name="TImplementation">服务实现类型</typeparam>
        public void RegisterSingleton<TInterface, TImplementation>()
            where TImplementation : class, TInterface, new()
        {
            _factories[typeof(TInterface)] = container => new TImplementation();
        }

        /// <summary>
        /// 注册单例服务（带工厂方法）
        /// </summary>
        /// <typeparam name="TInterface">服务接口类型</typeparam>
        /// <param name="factory">创建服务实例的工厂方法</param>
        public void RegisterSingleton<TInterface>(Func<ServiceContainer, TInterface> factory)
        {
            _factories[typeof(TInterface)] = container => factory(container);
        }

        /// <summary>
        /// 注册单例服务实例
        /// </summary>
        /// <typeparam name="TInterface">服务接口类型</typeparam>
        /// <param name="instance">服务实例</param>
        public void RegisterInstance<TInterface>(TInterface instance)
        {
            _services[typeof(TInterface)] = instance;
        }

        /// <summary>
        /// 获取服务实例
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns>服务实例</returns>
        public T GetService<T>()
        {
            var serviceType = typeof(T);
            
            // 首先检查是否已有实例
            if (_services.TryGetValue(serviceType, out var existingInstance))
            {
                return (T)existingInstance;
            }

            // 检查是否有工厂方法
            if (_factories.TryGetValue(serviceType, out var factory))
            {
                var newInstance = factory(this);
                _services[serviceType] = newInstance; // 缓存单例
                return (T)newInstance;
            }

            throw new InvalidOperationException($"服务 {serviceType.Name} 未注册");
        }

        /// <summary>
        /// 检查服务是否已注册
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns>如果已注册返回true，否则返回false</returns>
        public bool IsRegistered<T>()
        {
            var serviceType = typeof(T);
            return _services.ContainsKey(serviceType) || _factories.ContainsKey(serviceType);
        }

        /// <summary>
        /// 清空所有服务（主要用于测试）
        /// </summary>
        public void Clear()
        {
            _services.Clear();
            _factories.Clear();
        }

        /// <summary>
        /// 初始化默认服务
        /// </summary>
        public static void InitializeServices()
        {
            var container = Instance;
            
            // 注册配置服务
            container.RegisterSingleton<IConfigurationService>(c => new ConfigurationService());
            
            // 注册数据格式化服务
            container.RegisterSingleton<IDataFormattingService, DataFormattingService>();
            
            // 注册会话格式化服务
            container.RegisterSingleton<ISessionFormattingService>(c => 
                new SessionFormattingService(c.GetService<IDataFormattingService>()));
            
            // 注册会话服务
            container.RegisterSingleton<ISessionService>(c => 
                new SessionService(c.GetService<IConfigurationService>()));
            
            // 注册UI服务
            container.RegisterSingleton<IUIService>(c => 
                new UIService(
                    c.GetService<ISessionService>(),
                    c.GetService<IDataFormattingService>(),
                    c.GetService<ISessionFormattingService>(),
                    c.GetService<IConfigurationService>()));
        }
    }
}